/**
 * @file ls_file_common.h
 * @author lqy (you@domain.com)
 * @brief 
 * @version 0.1
 * @date 2022-06-13
 * 
 * @copyright Copyright (c) 2022
 * 
 */
#ifndef __LS_FILE_COMMON_H__
#define __LS_FILE_COMMON_H__

#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif

#include "ls_little_fs.h"
#include "ls_trace_common.h"



/**
 * @brief 读文件进buff
 * 
 */
static inline int32_t LS_FILE_COMMON_ReadFileInBuf(const char* _szFilePath, void* _pBuf, uint32_t _u32BufSize)
{
	lfs_file_t file;


	struct lfs_info info;
	int32_t s32Ret;
	uint8_t* pu8Buf = (uint8_t*)_pBuf;

	s32Ret= lfs_stat(ls_get_fs_config(),_szFilePath, &info);
	if(s32Ret != 0)
	{ 
		LS_TRACE_ERROR("tat %s failed by %d", _szFilePath,s32Ret); 
		return -1;
	}

	if(info.size > _u32BufSize){ 
		LS_TRACE_ERROR("_u32BufSize %u is too small expect %ld",_u32BufSize, info.size); 
		return -1;
	}


	s32Ret = lfs_file_open(ls_get_fs_config(), &file,_szFilePath, LFS_O_RDONLY);
	if(s32Ret != LFS_ERR_OK) 
	{ 
		LS_TRACE_ERROR("fopen %s failed by %d", _szFilePath,s32Ret);
		return -1;
	}


	int32_t s32BufLen = 0;
    while((s32Ret = lfs_file_read(ls_get_fs_config(), &file,pu8Buf + s32BufLen,1024)) > 0)
    {
    	s32BufLen += s32Ret;

		if(s32BufLen >= _u32BufSize)
		{
			break;
		}
    }

    s32Ret = lfs_file_close(ls_get_fs_config(), &file);
	if(s32Ret != 0) { 
		LS_TRACE_ERROR("fclose failed by %d",s32Ret);
		return -1;
	}
	

	return s32BufLen;
}




/**
 * @brief 写buff到文件
 * 
 */
static inline int32_t LS_FILE_COMMON_WriteBufInFile(char* _szFilePath,const void* _pBuf, uint32_t _u32BufSize)
{

    lfs_file_t file;
   
	if (_szFilePath == NULL)return -1;
	if(_pBuf == NULL)return -2;

	int  ret = lfs_file_open(ls_get_fs_config(), &file,_szFilePath, LFS_O_RDWR | LFS_O_CREAT);
	if(ret != LFS_ERR_OK) 
	{ 
		LS_TRACE_ERROR("error!");
		return -1;
	}

#define WRITE_SPEED (1024)

	int32_t s32Ret;
	int32_t s32WritenSize = 0;
	int32_t s32WritingSize;
	uint8_t* pu8Buf = (uint8_t*)_pBuf;
	while((uint32_t)s32WritenSize < _u32BufSize)
	{
		s32WritingSize = _u32BufSize - s32WritenSize > WRITE_SPEED ? WRITE_SPEED : _u32BufSize - s32WritenSize;
		s32Ret = lfs_file_write(ls_get_fs_config(), &file,pu8Buf + s32WritenSize,s32WritingSize);
		if(s32Ret != s32WritingSize)
		{
		
			break;
		}
		s32WritenSize += s32Ret;
	}

    lfs_file_close(ls_get_fs_config(), &file);
	return s32WritenSize;
}


#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif

#endif
